package com.yang.frost.raspberry.shiro;

import com.yang.frost.raspberry.shiro.jwt.JwtToken;
import com.yang.frost.raspberry.shiro.service.LoginRedisService;
import com.yang.frost.raspberry.shiro.vo.LoginSysUserRedisVo;
import org.apache.commons.collections4.SetUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;

/**
 * @author 10296
 * @date 2020/12/24
 * @Description: 自定义实现 ShiroRealm，包含认证和授权两大模块
 */
public class ShiroRealm extends AuthorizingRealm {


    private Logger logger = LoggerFactory.getLogger(ShiroRealm.class);
    @Autowired
    private LoginRedisService loginRedisService;


    @Override
    public boolean supports(AuthenticationToken token) {
//        return token != null && token instanceof JwtToken;

        return token instanceof JwtToken;
    }

    /**
     * 授权认证，设置角色/权限信息
     *
     * @param principalCollection 参数
     * @return 权限
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.info("doGetAuthorizationInfo  principalCollection...");

        /*这只角色/权限信息*/
        JwtToken jwtToken = (JwtToken) principalCollection.getPrimaryPrincipal();
        String username = jwtToken.getUsername();
        LoginSysUserRedisVo userRedisVo = loginRedisService.getLoginSysUserRedisVo(username);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(SetUtils.hashSet(userRedisVo.getRoleCode()));

        //设置权限
        simpleAuthorizationInfo.setStringPermissions(new HashSet<>());

        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.debug("doGetAuthenticationInfo authenticationToken...");
        JwtToken jwtToken = (JwtToken) authenticationToken;
        if (jwtToken == null) {
            throw new AuthenticationException("jwtToken不能为空！");
        }
        String salt = jwtToken.getSalt();
        if (StringUtils.isEmpty(salt)) {
            throw new AuthenticationException("salt不能为空");
        }
        return
                new SimpleAuthenticationInfo(jwtToken, salt, getName());
    }
}
